<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>超级管理员后台</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            font-weight: 300;
        }

        .content {
            padding: 40px;
        }

        .section {
            background: white;
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }

        .section h2 {
            color: #2c3e50;
            margin-bottom: 25px;
            font-size: 1.8rem;
            border-bottom: 3px solid #3498db;
            padding-bottom: 10px;
        }

        .search-container {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-bottom: 25px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 10px;
        }

        .search-container input,
        .search-container select {
            padding: 12px 15px;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s ease;
            min-width: 150px;
        }

        .search-container input:focus,
        .search-container select:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
        }

        .btn {
            padding: 12px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.3s ease;
            margin-right: 10px;
            margin-bottom: 10px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #3498db, #2980b9);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(52, 152, 219, 0.4);
        }

        .btn-success {
            background: linear-gradient(135deg, #27ae60, #229954);
            color: white;
        }

        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(39, 174, 96, 0.4);
        }

        .btn-warning {
            background: linear-gradient(135deg, #f39c12, #e67e22);
            color: white;
        }

        .btn-warning:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(243, 156, 18, 0.4);
        }

        .btn-danger {
            background: linear-gradient(135deg, #e74c3c, #c0392b);
            color: white;
        }

        .btn-danger:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(231, 76, 60, 0.4);
        }

        .btn-secondary {
            background: linear-gradient(135deg, #95a5a6, #7f8c8d);
            color: white;
        }

        .btn-secondary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(149, 165, 166, 0.4);
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }

        th {
            background: linear-gradient(135deg, #34495e, #2c3e50);
            color: white;
            padding: 15px;
            text-align: left;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 12px;
            letter-spacing: 1px;
        }

        td {
            padding: 15px;
            border-bottom: 1px solid #ecf0f1;
            transition: background-color 0.3s ease;
        }

        tr:hover td {
            background-color: #f8f9fa;
        }

        tr:last-child td {
            border-bottom: none;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #2c3e50;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .form-group input:focus,
        .form-group select:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            animation: fadeIn 0.3s ease;
        }

        .modal.active {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
            max-width: 500px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
            animation: slideIn 0.3s ease;
        }

        .modal h3 {
            color: #2c3e50;
            margin-bottom: 25px;
            font-size: 1.5rem;
            text-align: center;
        }

        .modal-buttons {
            display: flex;
            gap: 10px;
            justify-content: center;
            margin-top: 25px;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        @keyframes slideIn {
            from { transform: translateY(-50px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }

        .status-normal {
            color: #27ae60;
            font-weight: 600;
        }

        .status-disabled {
            color: #e74c3c;
            font-weight: 600;
        }

        .role-admin {
            color: #8e44ad;
            font-weight: 600;
        }

        .role-leader {
            color: #3498db;
            font-weight: 600;
        }

        .role-member {
            color: #95a5a6;
            font-weight: 600;
        }

        .add-dept-container {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-bottom: 25px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 10px;
        }

        .add-dept-container input {
            padding: 12px 15px;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s ease;
            min-width: 150px;
        }

        .add-dept-container input:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
        }

        .empty-state {
            text-align: center;
            padding: 40px;
            color: #95a5a6;
        }

        .empty-state i {
            font-size: 3rem;
            margin-bottom: 20px;
            display: block;
        }

        .loading {
            text-align: center;
            padding: 20px;
            color: #3498db;
        }

        .stats-card {
            background: linear-gradient(135deg, #3498db, #2980b9);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            text-align: center;
        }

        .stats-card h3 {
            margin: 0;
            font-size: 2rem;
        }

        .stats-card p {
            margin: 5px 0 0 0;
            opacity: 0.9;
        }

        .action-buttons {
            display: flex;
            gap: 5px;
            flex-wrap: wrap;
        }

        .action-buttons .btn {
            margin: 0;
            font-size: 12px;
            padding: 8px 12px;
        }

        @media (max-width: 768px) {
            .container {
                margin: 10px;
                border-radius: 15px;
            }

            .content {
                padding: 20px;
            }

            .search-container,
            .add-dept-container {
                flex-direction: column;
            }

            .search-container input,
            .search-container select,
            .add-dept-container input {
                min-width: 100%;
            }

            table {
                font-size: 12px;
            }

            th, td {
                padding: 10px 8px;
            }

            .action-buttons {
                flex-direction: column;
            }

            .action-buttons .btn {
                width: 100%;
                margin-bottom: 5px;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>超级管理员后台管理</h1>
        <p>系统管理与用户权限控制</p>
    </div>

    <div class="content">
        <!-- 统计信息 -->
        <div class="stats-card">
            <h3 id="totalUsers">0</h3>
            <p>总用户数</p>
        </div>

        <!-- 用户管理区域 -->
        <div class="section">
            <h2>👥 用户管理</h2>

            <!-- 查询区域 -->
            <div class="search-container">
                <input type="text" id="searchKeyword" placeholder="输入姓名或用户名">
                <input type="text" id="searchDeptId" placeholder="部门ID">
                <select id="searchRole">
                    <option value="">全部角色</option>
                    <option value="LEADER">组长</option>
                    <option value="MEMBER">组员</option>
                </select>
                <select id="searchStatus">
                    <option value="">全部状态</option>
                    <option value="1">正常</option>
                    <option value="0">禁用</option>
                </select>
                <button class="btn btn-primary" onclick="searchUsers()">🔍 查询</button>
                <button class="btn btn-success" onclick="loadAllUsers()">🔄 刷新用户</button>
            </div>

            <table id="usersTable">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>用户名</th>
                    <th>昵称</th>
                    <th>部门ID</th>
                    <th>部门名称</th>
                    <th>角色</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>

        <!-- 部门管理区域 -->
        <div class="section">
            <h2>🏢 部门管理</h2>

            <div class="add-dept-container">
                <input type="number" id="newDeptId" placeholder="输入部门ID">
                <input type="text" id="newDeptName" placeholder="新建部门名称">
                <input type="number" id="newDeptLeaderId" placeholder="组长ID">
                <button class="btn btn-success" onclick="addDept()">➕ 新增部门</button>
            </div>

            <table id="deptsTable">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>部门名称</th>
                    <th>组长ID</th>
                    <th>负责人</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </div>
</div>

<!-- 用户编辑弹窗 -->
<div id="editUserModal" class="modal">
    <div class="modal-content">
        <h3>✏️ 编辑用户</h3>
        <form id="editUserForm">
            <input type="hidden" id="editUserId">

            <div class="form-group">
                <label>昵称</label>
                <input type="text" id="editUserNickname" placeholder="请输入昵称">
            </div>

            <div class="form-group">
                <label>状态</label>
                <select id="editUserStatus">
                    <option value="1">正常</option>
                    <option value="0">禁用</option>
                </select>
            </div>

            <div class="form-group">
                <label>角色</label>
                <select id="editUserRole">
                    <option value="SUPER_ADMIN">超级管理员</option>
                    <option value="LEADER">组长</option>
                    <option value="MEMBER">组员</option>
                </select>
            </div>

            <div class="form-group">
                <label>部门</label>
                <select id="editUserDept">
                    <option value="">请选择部门</option>
                </select>
            </div>

            <div class="modal-buttons">
                <button type="submit" class="btn btn-primary">💾 保存</button>
                <button type="button" class="btn btn-secondary" onclick="closeUserModal()">❌ 取消</button>
                <button type="button" class="btn btn-warning" onclick="resetUserPassword()">🔑 重置密码</button>
            </div>
        </form>
    </div>
</div>

<!-- 部门编辑弹窗 -->
<div id="editDeptModal" class="modal">
    <div class="modal-content">
        <h3>✏️ 编辑部门</h3>
        <input type="hidden" id="editDeptId">

        <div class="form-group">
            <label>部门名称</label>
            <input type="text" id="editDeptName" placeholder="请输入部门名称">
        </div>

        <div class="form-group">
            <label>组长ID</label>
            <input type="number" id="editDeptLeaderId" placeholder="请输入组长ID">
        </div>

        <div class="modal-buttons">
            <button class="btn btn-primary" onclick="saveDept()">💾 保存</button>
            <button class="btn btn-secondary" onclick="closeDeptModal()">❌ 取消</button>
        </div>
    </div>
</div>

<script>
    /************ 用户管理 ************/
    function loadAllUsers(){
        const tbody = document.querySelector("#usersTable tbody");
        tbody.innerHTML = '<tr><td colspan="8" class="loading">🔄 加载中...</td></tr>';

        fetch('/api/admin/users')
            .then(res=>res.json())
            .then(res=>{
                if(res.code===200){
                    renderUsers(res.data);
                    loadAllDepts(); // 确保部门下拉刷新
                } else {
                    tbody.innerHTML = '<tr><td colspan="8" class="empty-state">❌ 加载失败：' + res.msg + '</td></tr>';
                }
            })
            .catch(err => {
                console.error("加载用户失败:", err);
                tbody.innerHTML = '<tr><td colspan="8" class="empty-state">❌ 网络错误，请检查连接</td></tr>';
            });
    }
    const roleMap = {
        "SUPER_ADMIN": "管理员",
        "MEMBER": "普通用户",
        "LEADER": "组长",
        // 根据你项目的角色再增加
    };
    function renderUsers(users){
        const tbody = document.querySelector("#usersTable tbody");
        tbody.innerHTML="";

        // 更新统计信息
        document.getElementById("totalUsers").textContent = users.length;

        if (users.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="8" class="empty-state">
                        <i>👥</i>
                        <p>暂无用户数据</p>
                    </td>
                </tr>
            `;
            return;
        }

        users.forEach(u=>{
            const userIdStr = u.id.toString();
            const deptIdStr = u.deptId ? u.deptId.toString() : "";
            const statusClass = u.status == 1 ? "status-normal" : "status-disabled";
            const roleClass = u.role === "SUPER_ADMIN" ? "role-admin" :
                u.role === "LEADER" ? "role-leader" : "role-member";

            tbody.innerHTML+=`
        <tr>
            <td>${userIdStr}</td>
            <td>${u.username}</td>
            <td>${u.nickname||""}</td>
            <td>${deptIdStr}</td>
            <td>${u.deptName||"未分配"}</td>
            <td class="${roleClass}">${roleMap[u.role] || u.role}</td>
            <td class="${statusClass}">${u.status==1?"正常":"禁用"}</td>
            <td>
                <div class="action-buttons">
                    <button class="btn btn-primary" onclick="openEditUser('${userIdStr}')">✏️ 编辑</button>
                    <button class="btn btn-danger" onclick="deleteUser('${userIdStr}')">🗑️ 删除</button>
                    <button class="btn btn-warning" onclick="resetPassword('${userIdStr}')">🔑 重置密码</button>
                </div>
            </td>
        </tr>
    `;
        });
    }

    function loadDeptOptions(selectedDeptId) {
        fetch("/api/admin/depts")
            .then(res => res.json())
            .then(res => {
                if(res.code === 200) {
                    const deptSelect = document.getElementById("editUserDept");
                    if (deptSelect) {
                        deptSelect.innerHTML = ""; // 清空旧的
                        res.data.forEach(d => {
                            const option = document.createElement("option");
                            option.value = d.id;
                            option.textContent = d.name;
                            if(selectedDeptId && selectedDeptId === d.id.toString()) {
                                option.selected = true;
                            }
                            deptSelect.appendChild(option);
                        });
                    }
                }
            })
            .catch(err => console.error("加载部门失败:", err));
    }


    // 模糊查询用户
    function searchUsers() {
        const keyword = document.getElementById("searchKeyword").value.trim();
        const role = document.getElementById("searchRole").value;
        const status = document.getElementById("searchStatus").value;
        const deptId = document.getElementById("searchDeptId").value.trim();

        // 构建查询参数
        let params = new URLSearchParams();
        if(keyword) params.append("keyword", keyword);
        if(role) params.append("role", role);
        if(status) params.append("status", status);
        if(deptId) params.append("deptId", deptId);

        fetch('/api/admin/users/search?' + params.toString())
            .then(res => res.json())
            .then(res => {
                if(res.code === 200){
                    renderUsers(res.data);
                } else {
                    alert("查询失败：" + res.msg);
                }
            });
    }


    function openEditUser(userId){
        fetch(`/api/admin/adminusers/${userId}`)
            .then(res=>res.json())
            .then(res=>{
                if(res.code===200){
                    const u = res.data;
                    document.getElementById("editUserId").value = u.id;
                    document.getElementById("editUserNickname").value = u.nickname || "";
                    document.getElementById("editUserStatus").value = u.status;
                    document.getElementById("editUserRole").value = u.role;

                    // 加载部门下拉框并选中用户的部门
                    loadDeptOptions(u.deptId ? u.deptId.toString() : "");
                    document.getElementById("editUserModal").classList.add("active");
                } else {
                    alert("获取用户失败：" + res.msg);
                }
            })
            .catch(err=>{
                console.error("获取用户失败:", err);
                alert("请求失败");
            });
    }

    function closeUserModal(){ document.getElementById("editUserModal").classList.remove("active"); }

    document.getElementById("editUserForm").onsubmit=function(e){
        e.preventDefault();
        const id = document.getElementById("editUserId").value;
        const nickname = document.getElementById("editUserNickname").value;
        const status = document.getElementById("editUserStatus").value;
        const role = document.getElementById("editUserRole").value;
        const deptId = document.getElementById("editUserDept").value;

        fetch(`/api/admin/adminusers/${id}`,{
            method:'PUT',
            headers:{"Content-Type":"application/json"},
            body:JSON.stringify({nickname, status:parseInt(status), role, deptId})
        })
            .then(res=>res.json())
            .then(res=>{
                if(res.code===200){
                    alert("修改成功");
                    closeUserModal();
                    loadAllUsers();
                }else alert("修改失败："+res.msg);
            });
    }

    // 删除用户
    function deleteUser(userId){
        if(!confirm("确定要删除该用户吗？")) return;
        fetch(`/api/admin/users/${userId}`,{method:'DELETE'})
            .then(res=>res.json())
            .then(res=>{
                if(res.code===200) loadAllUsers();
                else alert("删除失败："+res.msg);
            });
    }

    // 重置密码
    function resetPassword(userId){
        const defaultPwd = prompt("请输入新密码","");
        if(!defaultPwd) return;
        fetch(`/api/admin/users/${userId}/reset-password`,{
            method:'PUT',
            headers:{"Content-Type":"application/json"},
            body:JSON.stringify({password:defaultPwd})
        })
            .then(res=>res.json())
            .then(res=>{
                if(res.code===200) alert("密码已重置");
                else alert("重置失败："+res.msg);
            });
    }

    // 填充部门下拉
    function populateDeptOptions(selectedDeptId){
        fetch('/api/admin/depts')
            .then(res=>res.json())
            .then(res=>{
                if(res.code===200){
                    const sel = document.getElementById("editUserDept");
                    if (sel) {
                        sel.innerHTML="";
                        res.data.forEach(d=>{
                            const opt=document.createElement("option");
                            opt.value=d.id.toString();
                            opt.text=d.name;
                            if(d.id.toString() === selectedDeptId) opt.selected=true;
                            sel.add(opt);
                        });
                    }
                }
            });
    }

    /************ 部门管理 ************/
    function loadAllDepts(){
        const tbody = document.querySelector("#deptsTable tbody");
        tbody.innerHTML = '<tr><td colspan="5" class="loading">🔄 加载中...</td></tr>';

        fetch('/api/admin/depts')
            .then(res => res.json())
            .then(res => {
                if(res.code === 200){
                    renderDepts(res.data);
                } else {
                    tbody.innerHTML = '<tr><td colspan="5" class="empty-state">❌ 加载失败：' + res.msg + '</td></tr>';
                }
            })
            .catch(err => {
                console.error("加载部门失败:", err);
                tbody.innerHTML = '<tr><td colspan="5" class="empty-state">❌ 网络错误，请检查连接</td></tr>';
            });
    }

    function renderDepts(depts){
        const tbody = document.querySelector("#deptsTable tbody");
        tbody.innerHTML = "";

        if (depts.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="5" class="empty-state">
                        <i>🏢</i>
                        <p>暂无部门数据</p>
                    </td>
                </tr>
            `;
            return;
        }

        depts.forEach(d => {
            const deptIdStr = d.id.toString();
            const leaderIdStr = d.leaderId ? d.leaderId.toString() : "";

            tbody.innerHTML += `
        <tr>
            <td>${deptIdStr}</td>
            <td><strong>${d.name}</strong></td>
            <td>${leaderIdStr}</td>
            <td>${d.leaderName || "未分配"}</td>
            <td>
                <div class="action-buttons">
                    <button class="btn btn-primary edit-dept-btn"
                            data-id="${deptIdStr}"
                            data-name="${d.name}"
                            data-leaderid="${leaderIdStr}">✏️ 编辑</button>
                    <button class="btn btn-danger" onclick="deleteDept('${deptIdStr}')">🗑️ 删除</button>
                </div>
            </td>
        </tr>
    `;
        });

        document.querySelectorAll(".edit-dept-btn").forEach(btn => {
            btn.addEventListener("click", () => {
                const id = btn.dataset.id;
                const name = btn.dataset.name;
                const leaderId = btn.dataset.leaderid;
                openEditDept(id, name, leaderId);
            });
        });
    }

    function openEditDept(id, name, leaderId){
        document.getElementById("editDeptId").value = id;
        document.getElementById("editDeptName").value = name;
        document.getElementById("editDeptLeaderId").value = leaderId || "";
        document.getElementById("editDeptModal").classList.add("active");
    }

    function closeDeptModal(){
        document.getElementById("editDeptModal").classList.remove("active");
    }

    function addDept(){
        const id = document.getElementById("newDeptId").value;
        const name = document.getElementById("newDeptName").value.trim();
        const leaderId = document.getElementById("newDeptLeaderId").value;

        if(!id || !name || !leaderId) return alert("请输入部门ID、名称和组长ID");

        fetch('/api/admin/depts',{
            method:'POST',
            headers:{"Content-Type":"application/json"},
            body: JSON.stringify({id, name, leaderId})
        })
            .then(res => res.json())
            .then(res => {
                if(res.code === 200){
                    document.getElementById("newDeptId").value = "";
                    document.getElementById("newDeptName").value = "";
                    document.getElementById("newDeptLeaderId").value = "";
                    loadAllDepts();
                } else alert("新增失败：" + res.msg);
            });
    }

    function saveDept(){
        const id = document.getElementById("editDeptId").value;
        const name = document.getElementById("editDeptName").value.trim();
        const leaderId = document.getElementById("editDeptLeaderId").value;

        if(!id || !name || !leaderId) return alert("请输入部门ID、名称和组长ID");

        fetch(`/api/admin/depts/${id}`,{
            method:'PUT',
            headers:{"Content-Type":"application/json"},
            body: JSON.stringify({id, name, leaderId})
        })
            .then(res => res.json())
            .then(res => {
                if(res.code === 200){
                    closeDeptModal();
                    loadAllDepts();
                    loadAllUsers(); // 刷新用户表格部门显示
                } else alert("修改失败：" + res.msg);
            });
    }

    function deleteDept(id){
        if(!confirm("确定要删除该部门吗？")) return;
        fetch(`/api/admin/depts/${id}`,{method:'DELETE'})
            .then(res => res.json())
            .then(res => {
                if(res.code === 200){
                    loadAllDepts();
                    loadAllUsers();
                } else alert("删除失败：" + res.msg);
            });
    }

    // 页面初始化
    loadAllDepts();
    loadAllUsers();
</script>

</body>
</html>
